/** 
 * DefaultSimpleNameParser.java Created by iweerarathna on Aug 31, 2011.
 * 
 * Copyright (c) 2011 Virtusa Corporation. All Rights Reserved.<br><br>. 
 * 
 */
package org.uim.cricket.analyzer.parsers.misc.impl;

import org.uim.cricket.analyzer.parsers.misc.SimpleNameParsable;
import org.uim.cricket.entities.Player;
import org.uim.cricket.util.MyStringUtils;

/**
 * Separates one or two player string representation to respective
 * <code>Player</code> objects.
 * 
 * <p>As example, suppose input String is 
 * <code>"A Isuru (Sri Lanka) and B Madushanka (England)"</code>, 
 * then output player instances will be players with "A Isuru" and
 * "B Madushanka". Their respective countries will be embedded into
 * their Player objects, <b> if any found</b>.</p>
 * 
 * <p><b>Note:</b> The number of elements that can be in the returned Player[] array
 * is at most 2.</p>
 * 
 * @version 1.0
 * @author iweerarathna
 */
public class OneOrTwoSimpleNameParser implements SimpleNameParsable {

    @Override
    public Player[] parserNames(String source) {
        if (source == null || source.length() == 0) return null;
        int pos = source.indexOf(" and ");
        
        if (pos < 0) {
            Player p = this.getPlayer(source);
            return new Player[] {p};
        }
        
        String tmp = source.substring(0, pos).trim();
        Player[] ps = new Player[2];
        ps[0] = this.getPlayer(tmp);
        tmp = source.substring(pos + 5).trim();
        ps[1] = this.getPlayer(tmp);
        
        return ps;
    }

    private Player getPlayer(String source) {
        Player p = new Player();
        int ppos = source.indexOf('(');
        if (ppos > 0) {
            p.setTitleName(source.substring(0, source.indexOf('(')).trim());
            String country = MyStringUtils.inBetween(source, "(", ")");
            p.setCountry(country);
        } else {
            p.setTitleName(source);
        }
        return p;
    }
    
}
